package com.ma.common.utils;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTDecodeException;

import java.util.Date;

public final class JwtUtil {
    private JwtUtil(){}
    /**
     * 生成jwt字符串
     */
    public static String sign(Long userId,String info,long expireIn,String secret){
       try {
           Date date = new Date(System.currentTimeMillis() + expireIn * 1000);
           Algorithm algorithm = Algorithm.HMAC256(secret);
           return JWT.create()
                   //将userId保存在token里面
                   .withAudience(userId.toString())
                    //存放自定义数据
                   .withClaim("info",info)
                   .withExpiresAt(date)
                   //tokens的密钥
                   .sign(algorithm);
       }catch (Exception e){
           return null;
       }
    }
    /**
     * 根据token获取用户数据
     */
    public static String getInfo(String token){
        try{
            return JWT.decode(token).getClaim("info").asString();
        }catch (JWTDecodeException e){
            return null;
        }
    }
    /**
     * 根据token获取userId
     */
    public static Long getUserId(String token){
        try {
            String userId = JWT.decode(token).getAudience().get(0);
            return Long.parseLong(userId);
        }catch (JWTDecodeException e){
            return null;
        }
    }
    public static Boolean checkSign(String token,String secret){
        try{
            Algorithm algorithm = Algorithm.HMAC256(secret);
            JWTVerifier jwtVerifier = JWT.require(algorithm).build();
            jwtVerifier.verify(token);
            return true;
        }catch (JWTDecodeException e){
            return false;
        }
    }
}
